/**
 * 现代化移动端侧边栏管理器
 * 提供流畅的移动端导航体验
 */

class MobileSidebarManager {
    constructor() {
        this.sidebar = null;
        this.overlay = null;
        this.isOpen = false;
        this.isMobile = false;
        this.touchStartX = 0;
        this.touchStartY = 0;
        this.init();
    }
    
    init() {
        this.sidebar = document.querySelector('.spider-nav-sidebar');
        if (!this.sidebar) return;
        
        this.createMobileOverlay();
        this.setupEventListeners();
        this.handleResize();
        this.setupTouchGestures();
    }
    
    createMobileOverlay() {
        this.overlay = document.createElement('div');
        this.overlay.className = 'mobile-sidebar-overlay';
        this.overlay.innerHTML = `
            <div class="overlay-content">
                <div class="overlay-header">
                    <h3>导航菜单</h3>
                    <button class="close-sidebar-btn" aria-label="关闭菜单">
                        <span>✕</span>
                    </button>
                </div>
                <div class="overlay-menu">
                    ${this.generateMobileMenu()}
                </div>
            </div>
        `;
        
        document.body.appendChild(this.overlay);
    }
    
    generateMobileMenu() {
        const menuItems = [
            { icon: '📊', text: '蜘蛛概况', route: 'overview' },
            { icon: '📝', text: '蜘蛛日志', route: 'logs' },
            { icon: '📋', text: '蜘蛛列表', route: 'list' },
            { icon: '🛤️', text: '访问路径', route: 'paths' },
            { icon: '📄', text: '文章爬取', route: 'articles' },
            { icon: '🔍', text: '收录分析', route: 'indexing' },
            { icon: '🚀', text: '搜索引擎推送', route: 'push' },
            { icon: '⚙️', text: '设置', route: 'settings' },
            { icon: '🔧', text: '插件设置', route: 'plugin-settings' }
        ];
        
        return menuItems.map(item => `
            <a href="#${item.route}" class="mobile-nav-item" data-route="${item.route}">
                <span class="mobile-nav-icon">${item.icon}</span>
                <span class="mobile-nav-text">${item.text}</span>
                <span class="mobile-nav-arrow">→</span>
            </a>
        `).join('');
    }
    
    setupEventListeners() {
        // 窗口大小变化
        window.addEventListener('resize', () => {
            this.handleResize();
        });
        
        // 关闭按钮
        this.overlay.querySelector('.close-sidebar-btn').addEventListener('click', () => {
            this.closeSidebar();
        });
        
        // 遮罩层点击关闭
        this.overlay.addEventListener('click', (e) => {
            if (e.target === this.overlay) {
                this.closeSidebar();
            }
        });
        
        // 移动端菜单项点击
        this.overlay.querySelectorAll('.mobile-nav-item').forEach(item => {
            item.addEventListener('click', (e) => {
                e.preventDefault();
                const route = e.currentTarget.dataset.route;
                this.navigateToRoute(route);
                this.closeSidebar();
            });
        });
        
        // ESC键关闭
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && this.isOpen) {
                this.closeSidebar();
            }
        });
    }
    
    setupTouchGestures() {
        let startX = 0;
        let startY = 0;
        let currentX = 0;
        let currentY = 0;
        let isDragging = false;
        
        document.addEventListener('touchstart', (e) => {
            if (!this.isMobile) return;
            
            startX = e.touches[0].clientX;
            startY = e.touches[0].clientY;
            isDragging = false;
        });
        
        document.addEventListener('touchmove', (e) => {
            if (!this.isMobile) return;
            
            currentX = e.touches[0].clientX;
            currentY = e.touches[0].clientY;
            
            const deltaX = currentX - startX;
            const deltaY = currentY - startY;
            
            // 检测是否为水平滑动
            if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 50) {
                isDragging = true;
                
                // 从左侧边缘向右滑动打开侧边栏
                if (startX < 50 && deltaX > 0 && !this.isOpen) {
                    e.preventDefault();
                    this.openSidebar();
                }
                
                // 向右滑动关闭侧边栏
                if (this.isOpen && deltaX < -50) {
                    e.preventDefault();
                    this.closeSidebar();
                }
            }
        });
        
        document.addEventListener('touchend', () => {
            isDragging = false;
        });
    }
    
    handleResize() {
        const width = window.innerWidth;
        const wasMobile = this.isMobile;
        this.isMobile = width <= 768;
        
        if (wasMobile !== this.isMobile) {
            if (this.isMobile) {
                this.enableMobileMode();
            } else {
                this.disableMobileMode();
            }
        }
    }
    
    enableMobileMode() {
        this.sidebar.classList.add('mobile-mode');
        this.sidebar.style.display = 'none';
        
        // 添加移动端菜单按钮
        this.createMobileMenuButton();
    }
    
    disableMobileMode() {
        this.sidebar.classList.remove('mobile-mode');
        this.sidebar.style.display = '';
        this.closeSidebar();
        
        // 移除移动端菜单按钮
        const mobileBtn = document.querySelector('.mobile-menu-btn');
        if (mobileBtn) {
            mobileBtn.remove();
        }
    }
    
    createMobileMenuButton() {
        if (document.querySelector('.mobile-menu-btn')) return;
        
        const button = document.createElement('button');
        button.className = 'mobile-menu-btn';
        button.innerHTML = `
            <span class="hamburger">
                <span></span>
                <span></span>
                <span></span>
            </span>
            <span class="menu-text">菜单</span>
        `;
        
        button.addEventListener('click', () => {
            this.toggleSidebar();
        });
        
        document.body.appendChild(button);
    }
    
    toggleSidebar() {
        if (this.isOpen) {
            this.closeSidebar();
        } else {
            this.openSidebar();
        }
    }
    
    openSidebar() {
        if (!this.isMobile) return;
        
        this.isOpen = true;
        this.overlay.classList.add('active');
        document.body.classList.add('sidebar-open');
        
        // 添加打开动画
        setTimeout(() => {
            this.overlay.querySelector('.overlay-content').classList.add('slide-in');
        }, 10);
    }
    
    closeSidebar() {
        if (!this.isMobile) return;
        
        this.isOpen = false;
        this.overlay.querySelector('.overlay-content').classList.remove('slide-in');
        
        setTimeout(() => {
            this.overlay.classList.remove('active');
            document.body.classList.remove('sidebar-open');
        }, 300);
    }
    
    navigateToRoute(route) {
        // 触发路由导航
        if (window.SpiderSPARouter) {
            window.SpiderSPARouter.navigateTo(`#${route}`);
        } else {
            // 回退到传统导航
            window.location.hash = route;
        }
    }
}

// 创建全局实例
window.MobileSidebarManager = new MobileSidebarManager();

// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = MobileSidebarManager;
}
